#include "gldraw.h"
#include <iostream>
#include <fstream>
using namespace std;
void ResizeGL (int width,int height) {
		if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}
	viewPortX=width;
	viewPortY=height;
	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	gluOrtho2D (0,WORLD_WIDTH,0,WORLD_HEIGHT);
	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix

}


bool InitGL () {
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0, 0, 0, 0.7);							// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculati

	simulator2D.Init(WORLD_WIDTH,WORLD_HEIGHT);

	return true;
}


void DrawGL () {
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity ();

	simulator2D.DrawGrid();
	

	float timeSinceLastFrame=0.01f;
 	simulator2D.Advection(timeSinceLastFrame);
 	simulator2D.BodyForce(timeSinceLastFrame);
 	simulator2D.Projection(timeSinceLastFrame);

	simulator2D.DrawSpeedField();




	glutSwapBuffers ();
}

void IdleGL () {
	glutPostRedisplay ();
}

void MousePressGL (int button,int action,int mouseX,int mouseY) {

	if (button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN){
		mouseLastX=mouseX;
		mouseLastY=mouseY;
	}

	
}

void MouseMoveGL (int mouseX,int mouseY) {
	int iDX=mouseX-mouseLastX;
	int iDY=mouseY-mouseLastY;
	float dx=float(iDX)/viewPortX;
	float dy=float(iDY)/viewPortY;
	
	Vector2 dMove(dx,-dy);
	Vector2 startPos(float(mouseLastX)/viewPortX,float(viewPortY-mouseLastY)/viewPortY);

	simulator2D.AddVelocity(startPos*Vector2(WORLD_WIDTH,WORLD_HEIGHT),dMove*100.0f);

	
}

void KeyPressGL (unsigned char key,int mouseX,int mouseY) {
	if (key==' '){
		float timeSinceLastFrame=0.01f;
		simulator2D.Advection(timeSinceLastFrame);
 		simulator2D.BodyForce(timeSinceLastFrame);
 		simulator2D.Projection(timeSinceLastFrame);
	}
}


